﻿using CQRSFramework.Common.Serializer;
using CQRSFramework.Messages;
using RabbitMQ.Client;
using System.Text;

namespace CQRSFramework.RabbitMQ.Impl
{
    public class RabbitMQMessagePublisher : IMessagePublisher
    {
        private const string BROKER_NAME = "CQRSFramework";
        private readonly IRabbitMQPersistentConnection _rabbitMQPersistentConnection;
        private readonly IJsonSerializer _jsonSerializer;
        public RabbitMQMessagePublisher(IJsonSerializer jsonSerializer, IRabbitMQPersistentConnection rabbitMQPersistentConnection)
        {
            _jsonSerializer = jsonSerializer;
            _rabbitMQPersistentConnection = rabbitMQPersistentConnection;
        }
        public void Publish(QueueMessage message, string exchange, string routingKey)
        {
            if (!_rabbitMQPersistentConnection.IsConnected)
            {
                _rabbitMQPersistentConnection.TryConnect();
            }
            using (var chanel = _rabbitMQPersistentConnection.CreateModel())
            {
                var msg = Encoding.UTF8.GetBytes(_jsonSerializer.Serialize(message));
                chanel.ExchangeDeclare(
                    exchange: BROKER_NAME,
                    type: "topic",
                    durable: true,
                    autoDelete: false,
                    arguments: null);
                chanel.BasicPublish(
                    exchange: BROKER_NAME,
                    routingKey: routingKey,
                    basicProperties: null,
                    body: msg);
            }
        }
    }
}
